<?php

require_once 'Ext/Oauth/Login/Abstract.php';

class Ext_Oauth_Login_Adapter_Qq extends Ext_Oauth_Login_Abstract
{
    public function oauth()
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $bootstrap->bootstrap('view');
        $view = $bootstrap->getResource('view');
        $callbackUrl = $view->serverUrl().$view->url(array('module'=>'account', 'controller'=>'oauth', 'action'=>'show-form', 'adapter'=>'qq'),'default',true);
        
        $config = Ext_Config::getInstance()->getConfig("oauth");
        $consumerKey = $config->adapter->qq->consumerKey;
        $consumerSecret = $config->adapter->qq->consumerSecret;
        
        $accessToken = $this->getStorage()->setMember('qq_access_token')->read();
        if (!isset($accessToken)) {
            $front = Zend_Controller_Front::getInstance();
            $authorizationCode = $front->getRequest()->get('code');
            if (isset($authorizationCode)) {
                $config = array(
                    'siteUrl'            => "https://graph.qq.com/oauth2.0",
                    'callbackUrl'        => $callbackUrl,
                    'grantType'          => "code",
                    'clientId'           => $consumerKey,
                    'clientSecret'       => $consumerSecret,
                    'state'              => "1",
                );
                $oauth2 = new Ext_Oauth2($config);
                $oauth2->setAccessTokenUri("/token");

                $accessTokenString = $oauth2->requestAccessToken($authorizationCode);
                $accessTokenArray = array();
                $parts = explode('&', $accessTokenString);
                if(!$parts){
                    $parts = array();
                }
                foreach ($parts as $kvpair) {
                    $pair = explode('=', $kvpair);
                    $accessTokenArray[rawurldecode($pair[0])] = rawurldecode($pair[1]);
                }
                if(isset($accessTokenArray['access_token'])){
                    $accessToken = $accessTokenArray['access_token'];
                    
                    $this->getStorage()->setMember('qq_access_token')->write($accessToken);
                }
            }
        }
        
        if(!$accessToken){
            $config = array(
                'siteUrl'            => "https://graph.qq.com/oauth2.0",
                'clientId'           => $consumerKey,
                'responseType'       => "code",
                'requestedRights'    => "get_user_info",
                'callbackUrl'        => $callbackUrl,
            );
            $oauth2 = new Ext_Oauth2($config);
            $oauth2->setAuthentificationUri("/authorize");

            $oauth2->authorizationRedirect();
        }
        
        $result = array(
            'code'        => Ext_Oauth_Login_Result::FAILURE,
            'data'        => '',
            'messages'    => array(),
        );
        
        $options = array(
            'access_token'  => $accessToken,
        );
        $restClient = new Zend_Rest_Client("https://graph.qq.com");
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/oauth2.0/me', $options);
        $body = $response->getBody();
        preg_match("/\"openid\":\"([0-9a-zA-Z]+)\"/si", $body, $m);
        $openid = "";
        if(isset($m['1'])){
            $openid = $m['1'];
        }
        if(!$openid){
            $result['messages'][] = "An error occurred!";
            return new Ext_Oauth_Login_Result($result['code'], $result['data'], $result['messages']);
        }
        $result['data']['identity'] = $openid;
        
        $service = new Ext_Service_Qq($accessToken, $openid);
        $user = $service->getUser();
        $nickname = "";
        if(isset($user['nickname'])){
            $result['data']['nickname'] = $user['nickname'];
        }
        $result['result'] = Ext_Oauth_Login_Result::SUCCESS;
        $result['data']['site'] = 'qq';
        return new Ext_Oauth_Login_Result($result['code'], $result['data'], $result['messages']);
    }
    
}
